package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheCliten {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheCliten(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time, unit);
    }

    //逻辑过期
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //缓存穿透解决
    public <R,ID> R queryWithPassThrough(String preix, ID id, Class<R> type, Function<ID,R> dbFallback,Long time, TimeUnit unit){
        String key = preix + id;
        //1，从redis中查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2，判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3,存在，直接返回
            R bean = JSONUtil.toBean(json, type);
            return bean;
        }
        if (json != null){
            return null;
        }
        //4，不存在，根据id查数据库
        R r = dbFallback.apply(id);
        //5,DB 不存咋,返回
        if (r == null){
            //缓存控制，防止缓存穿透
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //6，DB 存在，放入redsi，并返回
        this.set(key,r,time,unit);
        return r;
    }

    private static final ExecutorService CACHE_BUILD_EXECYTOR = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1);
    //携带逻辑过期时间，
    public <R,ID> R queryWithLogicalExpire(String preix, ID id, Class<R> type,Function<ID,R> function,Long time, TimeUnit unit){
        String key = preix + id;
        //1，从redis中查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2，判断是否存在
        if (StrUtil.isBlank(json)) {
            //3,不存在，直接返回
            return null;
        }

        //4,存在则判断是否过期
        RedisData bean = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) bean.getData(), type);
        LocalDateTime expireTime = bean.getExpireTime();
        //5,未过期，则直接返回
        if (expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        //6，已过期，缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean islock = tryLock(lockKey);
        if (islock) { //获取锁成功，开启独立线程进行缓存重建
            CACHE_BUILD_EXECYTOR.submit(()-> {
                try {
                    //查数据库
                    R r1 = function.apply(id);
                    //重建缓存
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        //返回过期的数据
        return r;
    }

    private boolean tryLock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

}
